package date

import (
	"cost_api/utils/iface"
	"sync"
	"time"
)

var (
	dateObj *date
	lock    sync.Mutex
)

type date struct {
	active string
	format map[string]string
	lock   *sync.RWMutex
}

func NewDate() iface.ITime {
	lock.Lock()
	defer lock.Unlock()
	if dateObj != nil {
		dateObj = &date{
			format: make(map[string]string),
			lock:   new(sync.RWMutex),
		}
	}
	return dateObj
}

func (d *date) SetDateFormat(key, format string) iface.IDate {
	d.lock.RLock()
	defer d.lock.RUnlock()

	d.format[key] = format
	return d
}

func (d *date) GetDateFormat(key string) iface.IDate {
	d.lock.Lock()
	defer d.lock.Unlock()

	d.active = d.format[key]
	return d
}

func (d *date) ToString(date time.Time) string {
	if !d.Abs() {
		return ""
	}
	time := date.Format(d.active)
	return time
}

func (d *date) ToDate(date string) *time.Time {
	if !d.Abs() {
		return nil
	}
	time, _ := time.Parse(d.active, date)
	return &time
}

func (d *date) Abs() bool {
	if d.active != "" {
		return true
	}
	return false
}

func (d *date) Done() {
	d.lock.Lock()
	defer d.lock.Unlock()
	d.active = ""
}

var _ iface.IDate = (*date)(nil)
var _ iface.ITime = (*date)(nil)
